<template>
  <div>
    <el-form :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="用户状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in arrayStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="20">
      <!--     用户数据-->
      <el-col :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
            >修改</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-table :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="用户编号" align="center" prop="userId" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="手机号码" align="center" prop="phonenumber" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        lign="center"
        prop="createTime"
        :formatter="formatTimeCreateTime"
        width="160"
      />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template v-if="scope.row.userId !== 1" slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :normalizer="normalizer" :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                  v-for="dict in sexArrays"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in arrayStatus"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="form.postIds" multiple placeholder="请选择岗位">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">确 定</el-button>
        <el-button @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import axios from 'axios'
import Treeselect from '@riophae/vue-treeselect'
// import {addUser, updateUser} from "@/sysapi/sysuser";
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import dayjs from 'dayjs'

export default {
  name: 'Student12',
  components: {
    Treeselect
  },
  data() {
    return {
     // 选中数据
      ids: [],
      // 总条数
      total: 0,
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined
      },

      deptName: '',
      // 非单个禁用
      single: true,
      open: false,
      title: '添加员工信息',
      form: {},
      userList: [],
      // 部门数据
      deptOptions: [],
      // 岗位数据
      postOptions: [],
      // 角色数据
      roleOptions: [],
      sexArrays: [
        { label: '男', value: "0" },
        { label: '女', value: "1"},
        { label: '未知', value: "2" }
      ],
      arrayStatus: [
        { label: '正常', value: "0" },
        { label: '停用', value: "1" }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    deptName: function(val) {
      this.$refs.tree.filter(val)
      console.log('deptName', val)
    }
  },

  created() {
    this.getList()
    this.deptTree()
    this.getInof()
  },
  methods: {
    // normalizer(node) {
    //   return {
    //     id: node.deptId,     // 将节点的deptId映射为id
    //     label: node.deptName, // 将节点的deptName映射为label
    //     children: node.children // 子节点数组保持不变（如果存在）
    //   };
    // },

    // 进行数据 转换
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
      };
    },
    handleStatusChange(row) {
      // 修改用户状态
      return axios.put('http://localhost:9090/sysUser/changeStatus', null, {
          params: {
            userId: row.userId,
            status: row.status
          }
        }
      ).then(res => {
        this.$message.success("修改" + row.userName + "用户成功")
      }).catch(error => {
        this.$message.error("修改" + row.userName + "用户失败")
      })
    },

    // 时间格式化
    formatTimeCreateTime(row, column, cellValue) {
      // cellValue 是createTime字段的值
      if (!cellValue) return ''
      console.log('cellValue', cellValue)
      return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
    },
    handleQuery() {
      // 重置页码
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {}
      // this.getList()
      this.handleQuery()
    },
    // // 属性结构从新命令
    // transformTreeForFrontTend(treeData) {
    //   // 递归转换树形结构
    //   if (!treeData || typeof treeData !== 'object') return null
    //   // 遍历每个节点，创建新对象并重命字段
    //   return treeData.map(node => {
    //     // 必选字段， id （原deptId）, label（原deptName）
    //     const newNode = {
    //       id: node.deptId,
    //       label: node.deptName
    //     }
    //     // 可选字段， children（子节点）,递归转换子节点
    //     if (node.children && Array.isArray(node.children)) {
    //       newNode.children = this.transformTreeForFrontTend(node.children)
    //     }
    //     return newNode
    //   })
    // },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            this.updateUser(this.form).then(response => {
              // this.$modal.msgSuccess('修改成功')
              this.$message.success('修改成功')
              this.open = false
              console.log('open', this.open)
              this.getList()
            })
          } else {
            this.addUser(this.form).then(response => {
              // this.$modal.msgSuccess('新增成功')
              this.$message.success('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    updateUser(row) {
      return axios.put('http://localhost:9090/sysUser/edit', this.form).then(res => {
        const result = res.data.data
      })
    },
    addUser(row) {
      console.log('addUser', JSON.stringify(this.form))
      return axios.post('http://localhost:9090/sysUser/add', this.form).then(res => {
        const result = res.data.data
      })
    },
    handleDelete(row) {
      // http://localhost:9090/sysUser/?userId=20 这是不对的 params
      // http://localhost:9090/sysUser/20 这是不对的
      axios.delete('http://localhost:9090/sysUser/' + row.userId).then(res => {
        this.$message.success("删除成功")
        this.getList()
      })
    },
    handleUpdate(row) {
      this.open = true
      const userId = row.userId || this.ids;
      axios.get('http://localhost:9090/sysUser/'+userId).then(res => {
        this.form = res.data.data.data
        console.log("this.form1", this.form)
        this.$set(this.form, 'roleIds', res.data.data.roleIds);
        this.$set(this.form, 'postIds', res.data.data.postIds);

      })
      this.title = '修改用户'
      console.log("this.form2", this.form)
      console.log("dept1", this.deptOptions)
    },
    cancel() {
      this.open = false
      this.form = {}
    },
    handleAdd() {
      this.form = {},
      this.open = true
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 查询用户列表 */
    getList() {
      axios.get('http://localhost:9090/sysUser/selectPage', {
        params: this.queryParams
      }).then(res => {
        const result = res.data.data.list
        this.userList = result
        this.total = res.data.data.total
        console.log('total', this.total)
        // console.log("userList",this.userList)
      })
    },
    deptTree() {
      axios.get('http://localhost:9090/sysUser/deptTree').then(res => {
        const result = res.data.data
        console.log('deptTree', JSON.stringify(result))
        this.deptOptions = result;
      })
    },
    getInof() {
      axios.get('http://localhost:9090/sysUser/getInfo').then(res => {
        this.roleOptions = res.data.data.roles
        this.postOptions = res.data.data.posts
        console.log('getInof', this.roleOptions)
      })
    }
  }
}
</script>
